package cn.wen233.iocdemo.application.service.impl;

import cn.wen233.iocdemo.application.service.Esp8266Service;
import cn.wen233.iocdemo.domain.enums.LedState;
import cn.wen233.iocdemo.domain.enums.MotorState;
import cn.wen233.iocdemo.domain.model.DHT11;
import cn.wen233.iocdemo.infrustructure.util.MqttChannel;
import cn.wen233.iocdemo.infrustructure.util.TcpChannel;
import org.springframework.stereotype.Service;

/**
 * mqtt协议实现
 *
 * @author wenei
 * @date 2021-06-23 10:06
 */
@Service
public class MqttEsp8266ServiceImpl implements Esp8266Service {

    private static final String topic51 = "51Topic";

    private LedState curLedState = LedState.OFF;

    private MotorState curMotorState = MotorState.OFF;

    @Override
    public DHT11 dht11() {
        return new DHT11(MqttChannel.subscribe("dht11Topic"));
    }

    @Override
    public String ledControl(boolean status) {
        LedState state;
        if (status) {
            state = LedState.ON;
        } else {
            state = LedState.OFF;
        }
        String command = state.getCommand();
        String message = state.getMessage();
        curLedState = state;
        MqttChannel.asyncPublish(topic51, command);
        return message;
    }

    @Override
    public String motorControl(boolean status) {
        MotorState state;
        if (status) {
            state = MotorState.ON;
        } else {
            state = MotorState.OFF;
        }
        String command = state.getCommand();
        String message = state.getMessage();
        curMotorState = state;
        MqttChannel.asyncPublish(topic51, command);
        return message;
    }
}
